import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store/index'
import router from '@/router'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // 请求超时
})
const timeFlag = () => {
  return Date.now() - localStorage.getItem('time') > 50000000
}
// 请求拦截器
service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers.Authorization = `Bearer ${store.getters.token}`
    if (timeFlag()) {
      // token超时
      store.dispatch('user/logout')
      Message.error('登录超时')
      router.push('/login')
    }
    return config
  } else {
    return config
  }
})

// 响应拦截器
service.interceptors.response.use(res => {
  const { success, data, message } = res.data
  // 网络响应成功
  if (success) {
    // 网络和数据都成功
    return data
  } else {
    // 网络成功但是数据响应失败
    Message.error(message)
    return Promise.reject(new Error('错误'))
  }
}, err => {
  // 网络响应失败
  console.dir(err)
  // token失效
  if (err.response ? err.response.data.code === 10002 : false) {
    store.dispatch('user/logout')
    router.push('/login')
  }
  Message.error(err.message)
  return Promise.reject(err)
})

export default service
